const multer = require('multer');
const path = require('path');

// 文件类型验证
const fileFilter = (req, file, cb) => {
  if (file.fieldname === 'epub') {
    if (file.mimetype !== 'application/epub' && file.mimetype !== 'application/epub+zip') {
      cb(new Error('只允许上传epub格式的电子书文件'), false);
      return;
    }
  }
  cb(null, true);
};

// 配置文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = file.fieldname === 'epub' ? process.env.EPUB_PATH : process.env.COVER_PATH;
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    // 安全处理文件名
    const originalName = path.parse(file.originalname).name.replace(/[^a-zA-Z0-9]/g, '');
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, originalName + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({
  fileFilter,
  limits: {
    fileSize: 100 * 1024 * 1024 // 默认限制100MB
  },
  storage,
});

const fileSizeLimit = (req, res, next) => {
  if (req.files) {
    if (req.files.epub && req.files.epub[0].size > 100 * 1024 * 1024) {
      return res.status(400).json({
        code: 400,
        message: '电子书文件大小不能超过100MB'
      });
    }
    if (req.files.cover && req.files.cover[0].size > 5 * 1024 * 1024) {
      return res.status(400).json({
        code: 400,
        message: '封面图片大小不能超过5MB'
      });
    }
  }
  next();
};

module.exports = {
  upload,
  fileSizeLimit
};